package com.liming.system.controller.admin;

import com.alibaba.fastjson.JSON;
import com.liming.server.dto.LoginUserDto;
import com.liming.server.dto.PageDto;
import com.liming.server.dto.ResponseDto;
import com.liming.server.dto.UserDto;
import com.liming.server.service.UserService;
import com.liming.server.util.UuidUtil;
import com.liming.server.util.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/user")
public class UserController {
    public static final String BUSINESS_NAME="用户";
    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    public RedisTemplate redisTemplate;

    @PostMapping("/list")
    public ResponseDto list(@RequestBody PageDto pageDto){
        ResponseDto responseDto = new ResponseDto();
        userService.list(pageDto);
        responseDto.setContent(pageDto);
        return responseDto;
    }

    @PostMapping("/save")
    public ResponseDto save(@RequestBody UserDto userDto){

        //密码md5加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
        userDto.setPassword(md5DigestAsHex);

        //保存校验
        ValidatorUtil.require(userDto.getLoginName(),"登陆名");
        ValidatorUtil.length(userDto.getLoginName(),"登陆名",1,50);
        ValidatorUtil.length(userDto.getName(),"昵称",1,50);
        ValidatorUtil.require(userDto.getPassword(),"密码");

        ResponseDto responseDto = new ResponseDto();
        userService.save(userDto);
        responseDto.setContent(userDto);
        return responseDto;
    }

    @DeleteMapping("/delete/{id}")
    public ResponseDto delete(@PathVariable String id){
        ResponseDto responseDto = new ResponseDto();
        userService.delete(id);
        return responseDto;
    }

    /**
     * 重置密码
     * @param userDto
     * @return
     */
    @PostMapping("/save-password")
    public ResponseDto savePassword(@RequestBody UserDto userDto){

        //密码md5加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
        userDto.setPassword(md5DigestAsHex);

        ResponseDto responseDto = new ResponseDto();
        userService.savePassword(userDto);
        responseDto.setContent(userDto);
        return responseDto;
    }
    /**
     * 重置密码
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public ResponseDto login(@RequestBody UserDto userDto) {
        LOG.info("用户登录开始");
        //密码md5加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
        userDto.setPassword(md5DigestAsHex);
        ResponseDto responseDto = new ResponseDto();
        LOG.info("userDto :{}",userDto);

//        String imageCode = (String)request.getSession().getAttribute(userDto.getImageCodeToken());

        String imageCode = (String) redisTemplate.opsForValue().get(userDto.getImageCodeToken());
        LOG.info("redis中验证码 :{}",imageCode);

        if(StringUtils.isEmpty(imageCode)){
            responseDto.setSuccess(false);
            responseDto.setMessage("验证码已过期");
            LOG.info("用户登录失败，验证码已过期");
            return responseDto;
        }
        if (!imageCode.toLowerCase().equals(userDto.getImageCode().toLowerCase())) {
            responseDto.setSuccess(false);
            responseDto.setMessage("验证码不对");
            LOG.info("用户登录失败，验证码不对");
            return responseDto;
        } else {
            // 验证通过后，移除验证码
//             request.getSession().removeAttribute(userDto.getImageCodeToken());
            redisTemplate.delete(userDto.getImageCodeToken());
        }
        LoginUserDto loginUserDto = userService.login(userDto);
        String token = UuidUtil.getShortUuid();
        loginUserDto.setToken(token);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUserDto), 3600, TimeUnit.SECONDS);
//        request.getSession().setAttribute(Constants.LOGIN_USER, loginUserDto);
        responseDto.setContent(loginUserDto);
        return responseDto;
    }
     /** 退出登录
     * @param token
     * @return
     */
    @GetMapping("/logout/{token}")
    public ResponseDto logout(@PathVariable String token){
        //密码md5加密
        ResponseDto responseDto = new ResponseDto();
        redisTemplate.delete(token);
        LOG.info("redis中删除token :{}",token);
        return responseDto;
    }
}
